package com.study.springsecurity.controller;

import cn.hutool.jwt.JWT;
import com.study.springsecurity.service.UserService;
import com.study.springsecurity.utils.MyConstant;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.List;


/**
 * @Author: zzy
 * @Date: 2024/10/12 15:57
 * @Title:
 * @Version:
 * @Package: com.study.springsecurity.controller
 */
@RestController
@RequestMapping("/user")
@PreAuthorize("hasAuthority('author')")
public class UserController {
    @Resource
    AuthenticationManager authenticationManager;


    @GetMapping("/test")
    @PreAuthorize("hasAnyAuthority('author')")
    public String test() {
        return "tt";
    }

    @GetMapping("/test2")
    @PreAuthorize("hasAuthority('test2')")
    public String test2() {
        return "tt2";
    }


    @GetMapping("/login")
    public String login(@RequestParam(name = "account") String account, @RequestParam(name = "password") String password) {

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(account,password);
        authenticationManager.authenticate(authenticationToken);

        //上一步没有抛出异常说明认证成功，我们向用户颁发jwt令牌
        String token = JWT.create()
                .setPayload("username", account)
                .setKey(MyConstant.JWT_SIGN_KEY.getBytes(StandardCharsets.UTF_8))
                .sign();

        return token;
    }
}
